using System;
using System.Drawing;
using System.Windows.Forms;
using RebelStar.Engine.Sprites;
using Rectangle=Microsoft.Xna.Framework.Rectangle;

namespace RebelStar.Engine.GameView
{
    public class GameSpritePanel : Control
    {
        private SpriteBase sprite;
        private int spriteState;
        private bool selectable;
        private float scale;

        public GameSpritePanel() : this(1f)
        {}
        public GameSpritePanel(float scale)
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            this.scale = scale;
        }

        public SpriteBase Sprite
        {
            get { return sprite; }
        }
        public int SpriteState
        {
            get { return spriteState; }
        }
        public bool Selectable
        {
            get
            {
                return this.selectable;
            }
            set
            {
                this.selectable = value;
                this.SetStyle(ControlStyles.Selectable, value);
                this.Invalidate();
            }
        }

        public void SetSprite(SpriteBase sprite, int state)
        {
            this.sprite = sprite;
            this.spriteState = state;

            if (this.sprite != null)
                this.Size = new Size(
                    (int) (this.sprite.Width*scale),
                    (int) (this.sprite.Height*scale));

            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Pen pen = Pens.LightGray;
            if (this.selectable && this.Focused)
                pen = Pens.Black;

            e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);

            if (sprite == null) return;

            Rectangle state = sprite.GetState(spriteState);
            e.Graphics.DrawImage(
                sprite.Image,
                this.ClientRectangle,
                new System.Drawing.RectangleF(state.X, state.Y, state.Width, state.Height),
                GraphicsUnit.Pixel);
        }
        protected override void OnMouseClick(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                this.Focus();
        }
        protected override void OnGotFocus(EventArgs e)
        {
            this.Invalidate();
            base.OnGotFocus(e);
        }
        protected override void OnLostFocus(EventArgs e)
        {
            this.Invalidate();
            base.OnLostFocus(e);
        }
    }
}